import bencode, hashlib, base64, urllib.parse
def parse():
    torrent = open('liuyue.torrent', 'rb').read()
    metadata = bencode.bdecode(torrent)
    hashcontents = bencode.bencode(metadata['info'])
    digest = hashlib.sha1(hashcontents).digest()
    b32hash = base64.b32encode(digest).decode()
    print(b32hash)
    params = {'xt': 'urn:btih:%s' % b32hash,
          'dn': metadata['info']['name'],
          #'tr': metadata['announce'],
          #'xl': metadata['info']['length']
        }
    paramstr = urllib.parse.urlencode(params)
    magneturi = 'magnet:?%s' % paramstr
    return urllib.parse.unquote(magneturi)

parse()